import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

// 这个方法被dispatch时，有三种状态：pending、fullfilled、rejected
export const fetchHomeBannersAction = createAsyncThunk('fetchHomeBanners', async () => {
  const res = await axios.get("http://codercba.com:1888/api/home/hotSuggests")
  const list = res.data.data.map(item => item.tagText.text)
  return list
})


const homeSlice = createSlice({
  name: 'home',
  initialState: {
    banners: []
  },

  reducers: {
    getBanners(state, { payload }) {
      state.banners = payload
    }
  },
  extraReducers: {
    // 监听fetchHomeBannersAction状态
    // 可以只监听fulfilled状态
    [fetchHomeBannersAction.pending](state, action) {
      console.log('fetchHomeBannersAction pending');
    },
    [fetchHomeBannersAction.fulfilled](state, { payload }) {
      console.log('fetchHomeBannersAction fulfilled');
      state.banners = payload
    },
    [fetchHomeBannersAction.rejected]() {
      console.log('fetchHomeBannersAction rejected');
    }
  }
})

export const { getBanners } = homeSlice.actions
export default homeSlice.reducer